<script lang="ts" setup>
import navigateTo from '@/utils/navigator'

import type {IChapter, IEpisode} from '@/typings/interface'
import {isFreeEpisode} from '@/utils'

const {episode, play} = defineProps<{
    play?: boolean
    index: number
    chapter: IChapter
    episode: IEpisode
}>()
const {videoInfo, currentEpisodeId, changeEpisodeId} = $(useVideo())

// 正在播放文本显示与否
const active = $computed(() => play && episode.id === currentEpisodeId)

// 判断该集是否能观看
async function canToPlay() {
    return await isFreeEpisode(episode)
}

// 切换集
async function _changeEpisodeId() {
    // 如果没有观看权限则不跳转
    if (!await canToPlay()) return
    // 切换集
    changeEpisodeId(episode.id)

    if (play) {
        // 播放页的集切换
        uni.$emit('changeEpisodeId')
    } else {
        // 课程详情页点击集播放
        navigateTo(`/pages/player/index?id=${videoInfo?.id}&eid=${episode.id}`, {
            isNeedLogin: true
        })
    }
}
</script>

<template>
    <view between @click="_changeEpisodeId()">
        <view flex items-center truncate>
            <image v-if="active" flex-shrink-0 class="w-32 h-32"
                   src="@/static/images/icons/video/common/video_active.png"/>
            <image v-else flex-shrink-0 class="w-32 h-32" src="@/static/images/icons/video/common/video.png"/>
            <text ml-1 text-20 truncate :style="{ color: active ? '#f38e48' : '#666666' }">
                第 {{ index + 1 }} 节 - {{ episode.title }}
            </text>
        </view>
        <text v-show="!play && !episode.free" flex-shrink-0 text="20 red">
            试看
        </text>
        <view v-show="active" flex-shrink-0 bg="#ff4439" text="14 white" rounded-full px-2>
            正在播放
        </view>
    </view>
</template>

<style lang="scss" scoped></style>
